let box = new Vue({
  el: "#box",
  data: {
    itemList: [
      {
        id: 1,
        name: "iphone88 Pro Max",
        price: "199",
        data: "2011-4-12",
        buyNum: 1,
      },
      {
        id: 99,
        name: "HuaWei",
        price: "1998",
        data: "2021-6-1",
        buyNum: 2,
      },
      {
        id: 6,
        name: "iph Pro Max",
        price: "1889",
        data: "2011-4-12",
        buyNum: 3,
      },
      {
        id: 4,
        name: "iphone88 Pro Max",
        price: "199",
        data: "2011-4-12",
        buyNum: 1,
      },
    ],
    isAll: false,
    checkedList: [],
  },

  methods: {
    // 计算总价格
    calFee() {
      let curPrice = 0;

      let curList = this.itemList.filter((item) => {
        return this.checkedList.includes(item.id);
      });
      curList.forEach((item) => {
        curPrice += item.price * item.buyNum;
      });
      return curPrice;
    },

    // 减少
    decItem(curId) {
      // 指向同一个对象
      let curItem = this.itemList.find((item) => item.id == curId);
      if (curItem.buyNum > 0) curItem.buyNum--;
    },
    // 增加
    incItem(curId) {
      // 指向同一个对象
      let curItem = this.itemList.find((item) => item.id == curId);
      if (curItem.buyNum < 100) curItem.buyNum++;
    },

    // 删除商品
    delItem(curId) {
      // 找出索引下标
      let curItem = this.itemList.find((item) => item.id == curId);
      let index = this.itemList.indexOf(curItem);

      //删除元素
      this.itemList.splice(index, 1);

      // 若已被选中则在checkedList中删除
      if (this.checkedList.includes(curId)) {
        index = this.checkedList.indexOf(curId);
        this.checkedList.splice(index, 1);
      }

      this.caliAll();
    },

    // 全选按钮
    allChecked() {
      if (this.isAll) {
        this.checkedList = this.itemList.map((item) => {
          return item.id;
        });
      } else this.checkedList = [];
    },

    //校准isAll的值
    caliAll() {
      if (this.checkedList.length == this.itemList.length) this.isAll = true;
      else this.isAll = false;
    },
  },
});
